package com.caigou.service.impl;

import com.caigou.bean.cms.entity.AdConfig;
import com.caigou.bean.cms.entity.AdList;
import com.caigou.bean.cms.entity.AdOperationLog;
import com.caigou.bean.cms.param.AdConfigParam;
import com.caigou.bean.cms.param.AdListParam;
import com.caigou.bean.exam.entity.Users;
import com.caigou.component.HtmlBuildAdComponent;
import com.caigou.enums.ResponseEnum;
import com.caigou.mapper.cms.AdListMapper;
import com.caigou.pojo.AdConfigInfoAdList;
import com.caigou.pojo.AdConfigList;
import com.caigou.pojo.AdListHistory;
import com.caigou.pojo.AdListInfo;
import com.caigou.service.AdConfigService;
import com.caigou.service.AdListService;
import com.caigou.service.AdOperationLogService;
import com.caigou.util.DateUtil;
import com.caigou.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("adListService")
public class AdListServiceImpl implements AdListService {

    @Resource
    private AdOperationLogService adOperationLogService;
    @Resource
    private AdConfigService adConfigService;
    @Resource
    private AdListMapper adListMapper;

    @Resource
    private HtmlBuildAdComponent htmlBuildAdComponent;

    @Override
    public Result loadAdListHistory(AdListParam param) {
        PageHelper.startPage(param.getPage(), param.getSize());
        List<AdListHistory> adListHistoryList = adListMapper.loadAdListHistory(param);
        PageInfo<AdListHistory> list = new PageInfo<>(adListHistoryList);
        return Result.success(list);
    }

    @Override
    public Result recoverAdListHistory(AdListParam param, Users users) {
        int timeResult = loadTimeQuantum(param.getAdConfigId(),param.getStartTime(),param.getEndTime(),null);
        if (timeResult > 0) return Result.error(ResponseEnum.TIME_QUANTUM_ERROR);
        // 时间参数判定
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowData = format.format(new Date());
        long startTime = DateUtil.stringtoDate(param.getStartTime(),"yyyy-MM-dd").getTime();
        long endTime = DateUtil.stringtoDate(param.getEndTime(),"yyyy-MM-dd").getTime();
        long nowTime = DateUtil.stringtoDate(nowData,"yyyy-MM-dd").getTime();
        if (startTime < nowTime || endTime < nowTime || startTime == endTime) return Result.error(ResponseEnum.AD_LIST_TIME_ERROR);
        AdList adList = new AdList();
        adList.setId(param.getAdListId());
        adList.setStartTime(param.getStartTime());
        adList.setEndTime(param.getEndTime());
        adListMapper.recoverAdListHistory(adList);
        // 保存广告位数据（今天大于等于开始时间则设置状态为1）
        if (startTime == nowTime){// 开始时间选择的今天的话，则设置为当前广告位的状态为1
            AdConfig adConfig = adConfigService.loadAdConfigByAdList(param.getAdListId());
            // 设置当前广告位的广告位下架状态
            AdList currentList = adListMapper.loadDefaultAdList(adConfig.getId());
            adListMapper.updateAdListStatus(currentList.getId(), 0);
            // 设置恢复的广告位为上架状态
            adListMapper.updateAdListStatus(param.getAdListId(), 1);
            // 更新当前静态页
            htmlBuildAdComponent.buildAdHtml(adConfig.getAdCode());
        }
        // 保存当前操作记录
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(1);
        current.setActionType("恢复已下架预设广告");
        current.setUserId(users.getUserid());
        current.setAdConfigId(param.getAdConfigId());
        current.setAdContractId(0);
        current.setAdContractCode("");
        adOperationLogService.saveOperationData(current);
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public AdList loadAdListByConfig(Integer configId) {
        return adListMapper.loadAdListByConfig(configId);
    }

    @Override
    public void updateAdListStatus(Integer id, Integer adStatus) {
        adListMapper.updateAdListStatus(id,adStatus);
    }

    @Override
    public void updateAdListToDefault(Integer configId, Integer adStatus) {
        adListMapper.updateAdListToDefault(configId,adStatus);
    }

    @Override
    public int loadPublicCountByContract(Integer contractId) {
        return adListMapper.loadPublicCountByContract(contractId);
    }

    @Override
    public List<AdConfigInfoAdList> loadAdConfigInfoAdList(Integer configId) {
        return adListMapper.loadAdConfigInfoAdList(configId);
    }

    @Override
    public int loadTimeQuantum(Integer configId, String startTime, String endTime, Integer adListId) {
        return adListMapper.loadTimeQuantum(configId,startTime,endTime,adListId);
    }

    @Override
    public int loadContractQuantum(Integer configId, Integer contractId) {
        return adListMapper.loadContractQuantum(configId,contractId);
    }

    @Override
    public int saveAdList(Integer adConfigId, Integer contractId, String jumpUrl, Integer imgId, String imgUrl, String startTime, String endTime,Integer adStatus) {
        AdList adList = new AdList();
        adList.setAdConfigId(adConfigId);
        adList.setContractId(contractId);
        adList.setAdType(2);
        adList.setAdStatus(adStatus);
        adList.setJumpUrl(jumpUrl);
        adList.setImgId(imgId);
        adList.setImgUrl(imgUrl);
        adList.setStartTime(startTime);
        adList.setEndTime(endTime);
        return adListMapper.saveAdList(adList);
    }

    @Override
    public AdListInfo loadAdListInfo(Integer adListId) {
        return adListMapper.loadAdListInfo(adListId);
    }

    @Override
    public int updateAdListInfo(Integer adListId, String startTime, String endTime, String jumpUrl, Integer imgId, String imgUrl, Integer adStatus) {
        AdList adList = new AdList();
        adList.setId(adListId);
        adList.setAdStatus(adStatus);
        adList.setStartTime(startTime);
        adList.setEndTime(endTime);
        adList.setJumpUrl(jumpUrl);
        adList.setImgId(imgId);
        adList.setImgUrl(imgUrl);
        return adListMapper.updateAdListInfo(adList);
    }

    @Override
    public AdList loadAdListById(Integer adListId) {
        return adListMapper.loadAdListById(adListId);
    }

    @Override
    public AdList loadAdListByConfigAndContract(Integer configId, Integer contractId) {
        return adListMapper.loadAdListByConfigAndContract(configId,contractId);
    }

    @Override
    public void deleteAdList(Integer adListId) {
        adListMapper.deleteAdList(adListId);
    }

    @Override
    public List<AdList> loadAdListByTask() {
        return adListMapper.loadAdListByTask();
    }

    @Override
    public AdList loadAdListByAdConfigCode(String adConfigCode) {
        return adListMapper.loadAdListByAdConfigCode(adConfigCode);
    }

    @Override
    public Result loadSyncAdConfigList(AdListParam param, Users users) {
        List<AdConfigList> adConfigList = adConfigService.loadSyncAdConfigList(param.getAdConfigId(),param.getTitle(),param.getSortType());
        return Result.success(adConfigList);
    }

    @Override
    public Result updateAdListByConfig(AdListParam param, Users users) {
        AdList adList = adListMapper.loadAdListById(param.getAdListId());
        if (null == adList) return Result.error(ResponseEnum.AD_LIST_CHANGE_ERROR);
        if (adList.getAdStatus() == 1) Result.error(ResponseEnum.AD_LIST_CHANGE_ERROR);
        if (adList.getAdType() == 2){// 如果是预设广告进行发布时间判定
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String nowData = format.format(new Date());
            if (DateUtil.stringtoDate(adList.getStartTime(),"yyyy-MM-dd").getTime() < DateUtil.stringtoDate(nowData,"yyyy-MM-dd").getTime()) Result.error(ResponseEnum.AD_LIST_CHANGE_ERROR);
        }
        AdConfig adConfig = adConfigService.loadAdConfigByAdId(param.getAdConfigId());
        AdList useAdList = adListMapper.loadAdListByConfig(param.getAdConfigId());
        if (null != useAdList){
            // 关闭正在使用的广告
            adListMapper.updateAdListStatus(useAdList.getId(), 0);
            // 开启要替换的广告
            adListMapper.updateAdListStatus(param.getAdListId(),1);
            // 保存操作记录
            AdOperationLog adOperationLog = new AdOperationLog();
            adOperationLog.setModuleType(1);
            adOperationLog.setActionType(adList.getAdType() == 2 ? "手工更换默认广告" : "手工替换默认广告");
            adOperationLog.setUserId(users.getUserid());
            adOperationLog.setAdConfigId(param.getAdConfigId());
            adOperationLog.setAdContractId(0);
            adOperationLog.setAdContractCode("");
            adOperationLogService.saveOperationData(adOperationLog);

            // 更新当前广告位碎片
            htmlBuildAdComponent.buildAdHtml(adConfig.getAdCode());
        }
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public AdList loadDefaultAdList(Integer configId) {
        return adListMapper.loadDefaultAdList(configId);
    }

    @Override
    public int loadPublicCountByConfig(Integer configId) {
        return adListMapper.loadPublicCountByConfig(configId);
    }
}
